<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改知识管理')" />
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content pt-md">
        <form class="form-horizontal" id="form-knowMgt-edit" th:object="${gyKnowBaseMgt}">
            <input name="id" th:field="*{id}" type="hidden">
            <input name="knowType" type="hidden" id="treeId" th:field="*{knowType}"/>
            <input name="filePath" type="hidden" id="filePath" th:field="*{filePath}"/>
            <input name="fileName" type="hidden" id="fileName" th:field="*{fileName}"/>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">知识类型：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input name="knowTypeName" onclick="selectKnwoTypeTree()" id="treeName" type="text"
                               placeholder="请选择知识库类型"     th:field="*{knowBaseType.knowTypeName}"
                               class="form-control">
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">知识名称：</label>
                <div class="col-sm-8">
                    <input name="knowName" th:field="*{knowName}" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">知识库编号：</label>
                <div class="col-sm-8">
                    <input name="knowCode" readonly th:field="*{knowCode}" class="form-control" type="text" required>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">说明：</label>
                <div class="col-sm-8">
                    <input id="memo" name="memo" th:field="*{memo}" type="hidden">
                    <div id="editor" class="summernote"></div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">附件：</label>
                <div class=" col-sm-8">
                    <input type="file" name="file"  id="imgUpload" class="imgFile form-control">
                    <span class="help-block m-b-none">导入的文件大小请不要超过50M；</span>
                </div>

            </div>
        </form>
    </div>

    <div class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存
            </button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭
            </button>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: summernote-js"/>
    <th:block th:include="include :: bootstrap-fileinput-js" />


    <script th:inline="javascript">
        var prefix = ctx + "gy/knowMgt";
        $("#form-knowMgt-edit").validate({
            focusCleanup: true
        });
        var fileUrl= [[${gyKnowBaseMgt.filePath}]];
        var file_name= [[${gyKnowBaseMgt.fileName}]];
        function initialPreviewConfig() {
            var ext = fileUrl.substr(fileUrl.lastIndexOf('.') + 1)
            var extType = 'object'

            if (/(pdf)$/i.test(ext)) {
                extType = 'pdf'
            }

            if (/(bmp|gif|jpg|jpeg|png)$/i.test(ext)) {
                extType = 'image'
            }

            return [
                {
                    type: extType,
                     size: 8000,
                     caption: file_name,
                     filename: file_name,
                     url: fileUrl,
                     key: "123"
                },
            ]
        }

        $(function() {
            // 单图上传
            $("#singleFile").fileinput({
                uploadUrl: ctx + 'common/upload',
                maxFileCount: 1,
                autoReplace: true
            }).on('fileuploaded', function (event, data, previewId, index) {
                console.log('fs')
                var rsp = data.response;
                log.info("return url：" + rsp.url)
                log.info("reutrn fileName：" + rsp.fileName)
                log.info("reutrn newFileName：" + rsp.newFileName)
                log.info("return originalFilename：" + rsp.originalFilename)
            }).on('fileremoved', function (event, id, index) {
                console.log("fileremoved")
                $("input[name='" + event.currentTarget.id + "']").val('')
            })

            $('.summernote').summernote({
                placeholder: '请输入内容',
                height : 192,
                lang : 'zh-CN',
                followingToolbar: false,
                dialogsInBody: true,
                callbacks: {
                    onImageUpload: function (files) {
                        sendFile(files[0], this);
                    }
                }
            });
            var content = $("#memo").val();
            $('#editor').summernote('code', content);
            // ------------------
            $("#imgUpload")
                .fileinput({
                    language: "zh", //设置语言
                    uploadUrl:ctx + 'common/upload', //上传的地址
                    allowedFileExtensions: ["jpg", "png", "jpeg", "bmp","xls", "doc", "docx","ppt","zip","txt", "pdf"], //接收的文件后缀
                    theme: "fa",      // 主题设置
                      initialPreview: fileUrl,        // 初始预览区域显示的图片
                    initialPreviewAsData: true,
                    initialPreviewConfig:initialPreviewConfig(),
                    dropZoneEnabled: false,          // 禁止点击预览区域进行文件上传操作
                    maxFileCount: 1,                    // 最大上传为 1
                    maxFileSize: 51200,
                    otherActionButtons:'<button type="button" class="kv-file-down btn btn-xs btn-default"  onclick="download()" title="下载附件"><i class="fa fa-cloud-download"></i></button>',
                    showUpload: false,             // 不显示上传按钮，选择后直接上传
                    previewClass:"uploadPreview",
                    layoutTemplates: {
                        actionUpload: '',//去除上传预览缩略图中的上传图片
                        //actionZoom:'',   //去除上传预览缩略图中的查看详情预览的缩略图标
                        //actionDownload:'' //去除上传预览缩略图中的下载图标
                        actionDelete: '', //去除上传预览的缩略图中的删除图标
                    }
                })
                .on("change", function() {
                    // 清除掉上次上传的图片
                 //   $(".uploadPreview").find(".file-preview-frame:first").remove();
                //    $(".uploadPreview").find(".kv-zoom-cache:first").remove();
                })
                .on("filebatchselected", function(e, files) {
                    $(this).fileinput("upload");             // 文件选择完直接调用上传方法。
                })
                .on("fileuploaded", function(e, data, previewiId, index) {       // 上传完成后的处理
                    var form = data.form,
                        files = data.files,
                        extra = data.extra,
                        response = data.response,        // 响应
                        reader = data.reader;          // 文件对象

                    if (response.code == "0") {
                        $("#fileName").val(response.originalFilename)
                        $("#filePath").val(response.url)
                        var img = new Image();     // 这里上传的是图片，对图片处理获取图片的分辨率
                        img.src = response.url;
                        if (img.complete) {
                            $(this).attr("data-displayReso", img.width + "*" + img.height);
                        } else {
                            img.onload = function() {
                                $(this).attr("data-displayReso", img.width + "*" + img.height);
                            };
                        }
                    }
                });
            //------------------
        });

        function download(){
       //     window.location.href =fileUrl
            var elelink = document.createElement("a");
            elelink.style.display = 'none';
            elelink.target = '_blank';
            elelink.href =  $("#filePath").val();
            elelink.download =  $("#fileName").val();
            document.body.appendChild(elelink);
            elelink.click();
            document.body.removeChild(elelink);

        }

        function submitHandler() {
            if ($("#treeId").val() == null || $("#treeId").val() == "") {
                $.modal.alertWarning("请选择知识库类型！");
                return
            }
            if ($.validate.form()) {
                var sHTML = $('.summernote').summernote('code');
                $("#memo").val(sHTML);
                $.operate.saveTab(prefix + "/edit", $('#form-knowMgt-edit').serialize());
            }
        }
        // 上传文件
        function sendFile(file, obj) {
            var data = new FormData();
            data.append("file", file);
            $.ajax({
                type: "POST",
                url: ctx + "common/upload",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $(obj).summernote('editor.insertImage', result.url, result.fileName);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function(error) {
                    $.modal.alertWarning("图片上传失败。");
                }
            });
        }

        function selectKnwoTypeTree() {
            var treeId = $("#treeId").val();
            var knowType = $.common.isEmpty(treeId) ? "3" : $("#treeId").val();
            var url = prefix + "/selectKnowTypeTree/" + knowType;
            var options = {
                title: '选择知识库类型',
                width: "380",
                url: url,
                callBack: doSubmit
            };
            $.modal.openOptions(options);
        }


        function doSubmit(index, layero) {
            var body = $.modal.getChildFrame(index);
            $("#treeId").val(body.find('#treeId').val());
            $("#treeName").val(body.find('#treeName').val());
            $.modal.close(index);
        }
    </script>
</body>
</html>
